<template>
	<div class="user-address">
		<back-header>我的地址</back-header>
		<div class="user-address-container">
			<address-item
					v-for="item in addressList"
					:key="item.id"
					:addressItem="item"
					:isDefault="isDefault"
					@isDefaultUpdate="isDefaultUpdate"
			/>
		</div>
	</div>
</template>

<script>
	import UserAddress from '@/services/userAddress';
	import backHeader from '#/Public/backHeader';
	import addressItem from '#/UserAddress/addressItem';

	const _userAddress = new UserAddress();
	export default {
		name: "userAddress",
		data() {
			return {
				addressList: [],
				isDefault: 65957,
				from: ''
			}
		},
		beforeRouteEnter(to, from, next) {
			next(vm => {
				vm.from = from.name;
			})
		},
		created() {
			this.getAddressList();
			this.getDefaultAddress();
		},
		methods: {
			getAddressList() {
				_userAddress.getAddressList().then(res => {
					this.addressList = res.data;
				})
			},
			getDefaultAddress() {
				_userAddress.getDefaultAddress().then(res => {
					this.isDefault = res.data.id;
				})
			},
			isDefaultUpdate(value) {
				this.isDefault = value;
				_userAddress.setDefaultAddress(value).then(res => {
					if (this.from === 'purchase') {
						this.$router.push(this.from);
					}
				})
			}
		},
		components: {
			backHeader,
			addressItem
		}
	}
</script>
